<template>
	<view class="preview" v-if="currentInfo">
		<swiper :current="currentIndex" :interval="3000"
		:duration="1000" @change="swiperChange" circular>
			<swiper-item v-for="(i, index) in classList" :key="i._id">
				<image v-if="readImgs.includes(index)" :src="i.picurl"
				mode="aspectFill" @click="maskChange"></image>
			</swiper-item>			
		</swiper>
		
		<view class="mask" v-show="maskState">
			<view class="goBack" @click="goBack"
			:style="{top:getstatusBarHeight() + 'px'}">
				<uni-icons type="back" size="20" color="#fff"></uni-icons>
			</view>
			<view class="count">{{ currentIndex + 1 }} / {{classList.length}}</view>
			<view class="tiem">
				<uni-dateformat :date="Date.now()" format="hh:mm"></uni-dateformat>
			</view>
			<view class="date">
				<uni-dateformat :date="Date.now()" format="MM月/dd日"></uni-dateformat>
			</view>
			<view class="footer" v-if="currentInfo.score">
				<view class="box" @click="clickInfo">
					<uni-icons type="info" size="23"></uni-icons>
					<view class="text">信息</view>
				</view>
				
				<view class="box" @click="clickScore">
					<uni-icons type="star" size="23"></uni-icons>
					<view class="text">{{ currentInfo.score }}分</view>
				</view>
				
				<view class="box" @click="clickDownLoad">
					<uni-icons type="download" size="23"></uni-icons>
					<view class="text">下载</view>
				</view>
			</view>
		</view>
		
		<uni-popup ref="infoPopup" type="bottom" :safe-area="false">
			<view class="infoPopup">
				<view class="popHeader">
					<view></view>
					<view class="title">壁纸信息</view>
					<view class="close" @click="clickClose">
						<uni-icons type="closeempty" size="18"
						color="#999"></uni-icons>
					</view>
				</view>
				
				<scroll-view scroll-y="true" >
					<view class="content">
						<view class="row">
							<view class="label">壁纸ID：</view>
							<text selectable class="value">{{ currentInfo.classid }}</text>
						</view>
												
						<view class="row">
							<view class="label">分类：</view>
							<text class="value class">{{ name }}</text>
						</view>
												
						<view class="row">
							<view class="label">发布者：</view>
							<text class="value">{{ currentInfo.nickname }}</text>
						</view>
												
						<view class="row">
							<text class="label" >评分：</text>
							<view class='value roteBox'>
								<uni-rate readonly v-model="value" size="16"/>
								<text class="score">{{ currentInfo?.score }}分</text>
							</view>
						</view>
												
						<view class="row">
							<text class="label">摘要：</text>
							<view class='value'>
								{{ currentInfo.description }}
							</view>
						</view>
												
						<view class="row">
							<text class="label">标签：</text>
							<view class='value tabs'>
								<view class="tab" v-for="(item, index) in currentInfo.tabs" :key="item">
									{{ item }}
								</view>
							</view>
						</view>	
						
						<view class="copyright">
							声明：本图片来用户投稿，非商业使用，用于免费学习交流，如侵犯了您的权益，
							您可以拷贝壁纸ID举报至平台，邮箱513894357@qq.com，管理将删除侵权壁纸，维护您的权益。
						</view>
						
						<view class="safe-area-inset-bottom"></view>
					</view>
				</scroll-view>
			</view>
		</uni-popup>
		
		
		<!-- 评分弹窗 -->
		<uni-popup ref="scorePopup" type="center" :is-mask-click="false">
			<view class="scorePopup">
				<view class="popHeader">
					<view></view>
					<view class="title">{{ isScore?'已经评分':'壁纸评分' }}</view>
					<view class="close" @click="clickCloseScore">
						<uni-icons type="closeempty" size="18"
						color="#999"></uni-icons>
					</view>
				</view>
				
				<view class="content">
					<uni-rate v-model="userScore" :readonly="isScore" allowHalf></uni-rate>
					<text class="text">{{userScore}} 分</text>
				</view>
				
				<view class="footer">
					<button :disabled="!userScore || isScore" type="default" 
					size="mini" plain @click="submitScore">确认评分</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import { getstatusBarHeight } from "@/utils/system.js"
import { apiSubmitScore, apiWriteDownload, apiGetDetailWall } from '@/Api/api.js';
import {onLoad, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app"


const scorePopup = ref(null)
const userScore = ref(0)		//评分
const isScore = ref(false)			//确认评分
const infoPopup = ref(null)
const classList = ref([])
const currentId = ref(null)
const currentIndex = ref(0)
const readImgs = ref([])
const currentInfo = ref({}) 	//存储单一照片信息
const name = ref(null)			//存储分类标签

//缓存中取出图片信息
const storgClassList = uni.getStorageSync("storgClassList") || []

classList.value = storgClassList.map(i=>{
	return {
		...i,
		picurl:i.smallPicurl.replace("_small.webp",".jpg")
	}
})


onLoad(async (e)=>{
	name.value = e.name || "每日推荐"
	currentId.value = e.id
	// console.log(e);
	if(e.type == "share"){
		let res = await apiGetDetailWall({id:currentId.value})
		classList.value = res.data.map(i=>{
			return {
				...i,
				picurl:i.smallPicurl.replace("_small.webp",".jpg"),
			}
		})
		// console.log(e);
	}
	currentIndex.value = findIndexOf(currentId.value)
	currentInfo.value = getPicMessage(currentIndex.value)
	
	
	
	// console.log(currentInfo.value.classid);
	// console.log(currentInfo.value);
	readImages()
})

//轮播图切换
const swiperChange = (e) =>{
	// console.log(e.detail.current);
	currentIndex.value = e.detail.current
	currentInfo.value = getPicMessage(currentIndex.value)
	
	readImages()
	// console.log(readImgs.value);
	// console.log(currentInfo.value);
}


//获得当前图片的信息
function getPicMessage (index){
	// console.log(classList.value[index]);
	return classList.value[index]
}

//获得当前索引值
function findIndexOf(id){
	let index = classList.value.findIndex(i=>{
		return i._id == id
	})
	return index
}

//返回上一页 
function goBack(){
	uni.navigateBack({
		success() {
			
		},
		fail(err) {
			uni.reLaunch({
				url:"/pages/index/index"
			})
		}
	})
}

//遮罩层显示
	const maskState = ref(true)
	function maskChange(){
		maskState.value = !maskState.value
	}
	
//显示弹出层（底部弹出）
	function clickInfo(){
		infoPopup.value.open()
	}
	
//评分
	const value = ref(3.5)
	
//点击关闭
	function clickClose(){
		infoPopup.value.close()
	}
	
//评分弹窗
	function clickScore(){
		if(currentInfo.value.userScore){
			isScore.value = true
			userScore.value = currentInfo.value.userScore
		}
		scorePopup.value.open()
	}
	
//关闭评分弹窗
	const clickCloseScore = () =>{
		scorePopup.value.close()
		userScore.value = 0
		isScore.value = false
	}
	
//确认评分
	const submitScore = async() =>{
		uni.showLoading({
			title:"加载中"
		})
		
		const { classid,_id:wallId } = currentInfo.value
		let res = await apiSubmitScore({
			classid,
			wallId,
			userScore:userScore.value
		})
		
		uni.hideLoading()
		if(res.errCode == 0){
			uni.showToast({
				title:"评分成功",
				icon:'success'
			})
			classList.value[currentIndex.value].userScore = userScore.value
			uni.setStorageSync("storgClassList",classList.value)
			clickCloseScore()
		}
		
	}
	
//加载前后两张图片
	function readImages() {
		readImgs.value.push(
			currentIndex.value <= 0 ? classList.value.length-1 : currentIndex.value-1,
			currentIndex.value,
			currentIndex.value >= classList.value.length-1 ? 0 : currentIndex.value+1,
		)
		readImages.value = [... new Set(readImgs.value)]
	}
	
	
//点击下载
async function clickDownLoad () {
	// #ifdef H5
	
	uni.showModal({
		content:"右键下载图片",
		showCancel:false
	})
	// #endif
	
	// #ifndef H5
	
	try{
		
		uni.showLoading({
			title:"下载中...",
			mask:true
		})
		
		const { classid,_id:wallId } = currentInfo.value
		let res = await apiWriteDownload({
			classid,
			wallId
		})
		if (res.errCode != 0) throw res;
		
		uni.getImageInfo({
			src:currentInfo.value.picurl,
			success: (res)=>{
				
				uni.saveImageToPhotosAlbum({
					filePath:res.path,
					success: (res) => {
						console.log(res);
					},
					fail: (err)=>{
						console.log(err);
						if(err.errMsg == 'saveImageToPhotosAlbum:fail cancel'){
							uni.showToast({
								title:"保存失败，请重新下载",
								icon:"none"
							})
							return
						}
						
						uni.showModal({
							title:"提示",
							content:"需要相册授权",
							success: (res)=>{
								if(res.confirm){
									uni.openSetting({
										success: (setting) => {
											console.log(setting.authSetting['scope.userInfo']);
											if(setting.authSetting['scope.userInfo']){
												uni.showToast({
													title:"授权成功",
													icon:"none"
												})
											}else{
												uni.showToast({
													title:"授权失败",
													icon:"none"
												})
											}
										}
									})
								}
							}
						})
					},
	
					complete: () => {
						uni.hideLoading()
					}
					
				})
			}
		})
	}catch (err) {
		console.log(err);
		uni.hideLoading();
	}
	// #endif
}


//分享模块
onShareAppMessage((e)=>{
	// console.log(e);
	return {
		title:"壁纸推荐—su",
		path:"/pages/preview/preview?id="
		+currentId.value+"&type=share"+"&name="+name.value,
		// imageUrl:'/static/xxmLogo.png'
	}
})

//分享朋友圈
onShareTimeline((e) =>{
	return {
		title:"壁纸推荐~su",
		query:"id="+currentId.value+"&type=share"+"&name="+name.value,
		imageUrl:'/static/xxmLogo.png'
	}
})  
	
</script>

<style lang="scss" scoped>
.preview{
	width: 100%;
	height: 100vh;
	position: relative;
	swiper{
		width: 100%;
		height: 100%;
		image{
			width: 100%;
			height: 100%;
		}
	}
	
	.mask{
		&>view{
			position: absolute;
			left: 0;
			right: 0;
			margin: auto;
			color: #fff;
			width: fit-content;
		}
		.goBack{
			width: 38px;
			height: 38px;
			background: rgba(0, 0, 0, 0.5);
			left: 30rpx;
			top: 0;
			margin-left: 0;
			border-radius: 100px;
			backdrop-filter: blur(10rpx);
			border: 1rpx solid rgba(255, 255, 255, 0.3);
			display: flex;
			justify-content: center;
			align-items: center;
		}
		.count{
			top: 10vh;
			color: #fff;
			background: rgba(0, 0, 0, 0.3);
			backdrop-filter: blur(10rpx);
			font-size: 30rpx;
			border-radius: 40rpx;
			padding: 8rpx 28rpx;
		}
		.tiem{
			font-size: 140rpx;
			top: calc(10vh + 80rpx);
			font-weight: 100;
			line-height: 1em;
			box-shadow: 0 4rpx rgba(0, 0, 0, 0.2);
		}
		.date{
			font-size: 34rpx;
			top: calc(10vh + 230rpx);
			box-shadow: 0 2rpx rgba(0, 0, 0, 0.2);
		}
		.footer{
			background-color: rgba(255, 255, 255, 0.6);
			bottom: 10vh;
			width: 60vw;
			height: 120rpx;
			border-radius: 120rpx;
			color: #000;
			display: flex;
			justify-content: space-around;
			align-items: center;
			box-shadow: 0 2rpx 0 rgba(0, 0, 0, 0.1);
			backdrop-filter: blur(20rpx);
			.box{
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 2rpx 16rpx;
				// border: 1rpx solid red;
				.text{
					font-size: 26rpx;
					color: $text-font-color-2;
				}
			}
		}
	}
	
	.popHeader{
		display: flex;
		justify-content: space-between;
		lign-items: center;
		.title{
			padding-left: 30rpx;
			color: $text-font-color-2;
		}
		.close{
			// border: 1rpx solid red;
			padding: 6rpx;
		}
	}
	
	.infoPopup{
		background:#fff;
		padding: 30rpx;
		border-radius: 50rpx 50rpx 0 0;
		overflow: hidden;
		scroll-view{
			max-height: 50vh;
			.content{
				.row{
					display: flex;
					padding: 16rpx 0;
					font-size: 32rpx;
					line-height: 1.7em;
					.label{
						color: $text-font-color-3;
						width: 170rpx;
						text-align: 30rpx;
						font-size: 30rpx;
					}
					.value{
						flex: 1;
						width: 0;
					}
					.roteBox{ //星星评分
						display: flex;
						align-items: center;
						.score{
							font-size: 28rpx;
							color: $text-font-color-2;
							padding-left: 10rpx;
						}
					}
						
					.tabs{
						display: flex;
						flex-wrap: wrap;
						.tab{
							font-size: 24rpx;
							color: $brand-theme-color;
							line-height: 1em;
							padding: 10rpx 20rpx;
							margin-right: 0 10rpx 10rpx 0;
							border: 1px solid $brand-theme-color;
							border-radius: 40rpx;
						}
					}
					.class{
						color: $brand-theme-color;
					}	
				}
			}
				.copyright{
					font-size: 28rpx;
					padding: 20rpx;
					background: #f6f6f6;
					color: #666;
					border-radius: 10rpx;
					margin: 20rpx 0;
					line-height: 1.2em;
				}
			}
	}
	
	
	.scorePopup{
		background: #fff;
		padding: 30rpx;
		width: 70vw;
		border-radius: 30rpx;
		.content{
			padding: 30rpx 0;
			display: flex;
			justify-content: center;
			align-items: center;
			.text{
				color: #ffca3e;
				padding-left: 10rpx;
				width: 80rpx;
				line-height: 1em;
				text-align: right;
			}
		}
		
		.footer{
			padding: 10rpx 0;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}
}
</style>
